package com.uit.gis.util;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class OracleDataAccessHelper {
	private Connection connection;
	private boolean connectionStatus = false;
	protected void open() {
		try { 
			Driver driver = new oracle.jdbc.driver.OracleDriver();
			DriverManager.registerDriver(driver);
			String conString = "jdbc:oracle:thin:sample_schema/oracle_pass@localhost:1521:xe";
			this.setConnection(DriverManager.getConnection(conString));

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

	}
	public ConnectionStatus open(String hostname,String port,String sId,String username, String password)
	{
		ConnectionStatus result = new ConnectionStatus();
		try { 
			Driver driver = new oracle.jdbc.driver.OracleDriver();
			DriverManager.registerDriver(driver);
			String conString ="jdbc:oracle:thin:"+username+"/"+password+"@"+hostname+":"+port+":"+sId; 
			this.setConnection(DriverManager.getConnection(conString));
			result.isConnected = true;

		} catch (Exception ex) { 
			result.errorString = ex.getMessage();
			result.isConnected = false; 
		}
		this.connectionStatus = result.isConnected;
		return result;
	}

	public void close() {
		try {
			this.getConnection().close();

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

	}

	public ResultSet executeQuery(String sql) {
		ResultSet rs = null;
		try {
			Statement sm = this.getConnection().createStatement();
			rs = sm.executeQuery(sql);

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return rs;
	}

	public int executeUpdate(String sql) {
		int n = -1;
		try {
			Statement sm = this.getConnection().createStatement();
			n = sm.executeUpdate(sql);
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return n;
	}
	public int executeCreate(String sql)
	{
		int n = -1;
		try {
			Statement sm = this.getConnection().createStatement();
			 sm.execute(sql);
			 n = 1;
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return n;
	}
	public boolean isConnected() {
		return connectionStatus;
	}
	public Connection getConnection() {
		return connection;
	}
	public void setConnection(Connection connection) {
		this.connection = connection;
	}
	 
}
